<?php
/**
 * User: b179a9
 * Date: 10/13/11
 * Time: 7:53 PM
 */

class PagesController extends Zend_Controller_Action
{
    /**
     * FlashMessenger
     *
     * @var Lib_Flash
     */
    protected $_flashMessenger = null;

    public function init()
    {
        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout()->disableLayout();
        } else {
            $this->_helper->layout()->setLayout('admin-layout');
        }
        $this->_flashMessenger = new Lib_Flash();
    }

    public function __call($name, $args)
    {
        $this->_forward('index');
    }

    public function indexAction()
    {
        $pagesManager = new \Managers\Statics();
        $pages = $pagesManager->getAllPages();

        $this->view->pages = $pages;
    }

    public function editAction()
    {
        $id = $this->_request->getParam('id');
        $pagesManager = new \Managers\Statics();
        $page = $pagesManager->getById($id);
        if (!$page) {
            $this->_flashMessenger->addMessage('Page does not exist.', Lib_Flash::ERROR, Lib_Flash::REDIRECT);
            $this->_redirect('/pages');
        }

        $form = new App_Form_Page_Form();
        $form->populate($page);

        if ($this->_request->isPost()) {
            if ($form->isValid($this->_request->getParams())) {
                $values = $form->getValues();
                try {
                    $pagesManager->save($values);
                    $this->_flashMessenger->addMessage('Page successfully updated.', Lib_Flash::NOTICE, Lib_Flash::REDIRECT);
                    $this->_redirect('/pages');
                } catch (Exception $e) {
                    $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::NOW);
                }
            } else {
                $this->_flashMessenger->addMessage('Please, check input data.', Lib_Flash::ERROR, Lib_Flash::NOW);
            }
        }

        $this->view->form = $form;
    }


}
